package m.jclecai.com.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import butterknife.OnClick;
import m.jclecai.com.R;

import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import m.jclecai.com.adapter.AccountParticularsAdapter;
import m.jclecai.com.adapter.PopWindowAdapter;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.AccountBaseBean;
import m.jclecai.com.bean.AccountParticularsBean;
import m.jclecai.com.bean.GroupBuyBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.DateUtil;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.ScreenUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.view.BallGridView;

public class BalanceActivity extends BaseActivity implements View.OnClickListener, PullToRefreshBase.OnRefreshListener2 {
    private BallGridView gridview;
    private PopupWindow pw;
    private Integer pager = 0;
    private PopWindowAdapter heMaiPopuWindowAdapter;
    private List<String> lx = new LinkedList<String>();
    private ListView mListView;
    private PullToRefreshListView pull_list;
    private AccountParticularsAdapter adapter;
    private LinearLayout ll_no_data;
    LinearLayout ll_no_network;
    private LinearLayout ll_pull;
    int page = 1;
    List<AccountParticularsBean> records;
    String type = "";

    @Override
    public int getContentView() {
        return R.layout.activity_balance;
    }

    @Override
    public void initData() {

    }

    @Override
    public void initView() {
        leftOptionText("");
        setTitle("账户明细", R.drawable.gs);
        records = new ArrayList<>();
        pull_list = (PullToRefreshListView) findViewById(R.id.pull_list);
        pull_list.setOnRefreshListener(this);
        pull_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //P T G==> 自购 追号 合买
                //其他都打开账目详情
                //一致认为 以projectno 判断
                AccountParticularsBean bean = records.get(position - 1);
                GroupBuyBean gb = new GroupBuyBean(bean.getPid(), bean.getProjectno());
                if(bean.getProjectno().startsWith("P")){
                    startActivity(new Intent(BalanceActivity.this, BuyDetailActivity.class)
                            .putExtra("bean", JSON.toJSONString(gb)));
                }else if(bean.getProjectno().startsWith("T")){
                    startActivity(new Intent(BalanceActivity.this, ChaseRecordListActivity.class)
                            .putExtra("bean", JSON.toJSONString(gb)));
                }else if(bean.getProjectno().startsWith("G")){
                    startActivity(new Intent(BalanceActivity.this, GroupBuyDetailActivity.class)
                            .putExtra("bean", JSON.toJSONString(gb)));
                }else {
                    startActivity(new Intent(BalanceActivity.this, WithdrawDetailActivity.class)
                            .putExtra("bean", JSON.toJSONString(bean)));
                }
            }
        });

        adapter = new AccountParticularsAdapter(BalanceActivity.this, records);
        mListView = pull_list.getRefreshableView();
        mListView.setDivider(null);
        mListView.setAdapter(adapter);
        ll_no_network = (LinearLayout) findViewById(R.id.ll_no_network);
        ll_no_data = (LinearLayout) findViewById(R.id.ll_no_data);
        ll_pull = (LinearLayout) findViewById(R.id.ll_pull);
        if (BaseUtils.netWork(this)) {
            ll_no_network.setVisibility(View.GONE);
            Data();
        } else {
            ll_no_network.setVisibility(View.VISIBLE);
            ll_pull.setVisibility(View.GONE);
        }
        lx.add("0");
        iniPopupWindow();
        showLoadingLayout(pull_list);
    }

    private void Data() {
        String userName = PreferenceUtil.getUserName(this);
        String password = PreferenceUtil.getPassword(this);
        UserBean userBean = PreferenceUtil.readUser(this);

        final HashMap<String, String> pair = new HashMap<>();
        pair.put("user", userName);
        pair.put("password", password);
        pair.put("page", String.valueOf(page));
        pair.put("type", type);
        pair.put("etime", DateUtil.getCurrTime("yyyy-MM-dd"));
        pair.put("stime", DateUtil.formatDate(userBean.getAddtime(), "yyyy-MM-dd"));
        HttpManager.postAsyn(Constant_Url.ACCOUNT_PARTICULARS_URL, new HttpManager.StringCallback() {

            @Override
            public void onFailure(Request request, IOException e) {
                pull_list.onRefreshComplete();
                showInternetOffLayout();
            }

            @Override
            public void onResponse(String response) {
                pull_list.onRefreshComplete();
                closeLoadingLayout();
                if (!TextUtils.isEmpty(response)) {
                    AccountBaseBean accountBaseBean = FastOk.get(response, AccountBaseBean.class);
                    if (accountBaseBean != null && "0".equals(accountBaseBean.getStatus())) {
                        records.addAll(accountBaseBean.getRecords());
                        if (records == null && records.size() == 0) {
                            ll_no_data.setVisibility(View.VISIBLE);
                            ll_pull.setVisibility(View.GONE);
                        } else {
                            ll_no_data.setVisibility(View.GONE);
                            ll_pull.setVisibility(View.VISIBLE);
                            adapter.notifyDataSetChanged();
                            if (page > accountBaseBean.getPages())
                                pull_list.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            if (accountBaseBean.getRecords().size() > 0)
                                page++;
                        }
                    }
                }
                if (records.size() <= 0)
                    showEmptyLayout();
            }
        }, pair);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void iniPopupWindow() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View conentView = inflater.inflate(R.layout.fragment_hemai_popuwindow, null);
        int w = ScreenUtil.getScreenWidth(this);
        gridview = (BallGridView) conentView.findViewById(R.id.gridview);
        String[] names = getResources().getStringArray(
                R.array.balance_types_name_list);
        String[] types = getResources().getStringArray(R.array.balance_types_list);
        heMaiPopuWindowAdapter = new PopWindowAdapter(this, names, types, lx);
        gridview.setAdapter(heMaiPopuWindowAdapter);
        gridview.measure(View.MeasureSpec.UNSPECIFIED,
                View.MeasureSpec.UNSPECIFIED);
        pw = new PopupWindow(conentView, w, gridview.getMeasuredHeight() + 10);
        // 设置SelectPicPopupWindow弹出窗体可点击
        pw.setFocusable(true);
        pw.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.listview_item_shaung));
        pw.setOutsideTouchable(true);


        pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(BalanceActivity.this, 1f);
            }
        });

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                lx.clear();
                TextView txt = (TextView) view
                        .findViewById(R.id.txt_hemai_popuwindow);
                String s = txt.getTag().toString();
                pager = Integer.valueOf(s);
                execData();
                switch (position) {
                    case 0:
                        setTitle("账户明细");
                        lx.add("0");
                        heMaiPopuWindowAdapter.notifyDataSetChanged();
                        break;
                    case 1:
                        setTitle("账户明细");
                        lx.add("1");
                        heMaiPopuWindowAdapter.notifyDataSetChanged();
                        break;
                    case 2:
                        setTitle("账户明细");
                        lx.add("2");
                        heMaiPopuWindowAdapter.notifyDataSetChanged();
                        break;
                    case 3:
                        setTitle("账户明细");
                        lx.add("3");
                        heMaiPopuWindowAdapter.notifyDataSetChanged();
                        break;
                }
                if (pw.isShowing()) {
                    pw.dismiss();
                }
            }
        });
        // 刷新状态
        pw.update();
    }

    public void execData() {
        showLoadingLayout(pull_list);
        pull_list.setMode(PullToRefreshBase.Mode.BOTH);
        page = 1;
        records.clear();
        adapter.notifyDataSetChanged();
        switch (pager) {
            case 0:
                type = "";
                Data();
                break;
            case 1:
                type = "6";
                Data();
                break;
            case 2:
                type = "5";
                Data();
                break;
            case 3:
                type = "7";
                Data();
                break;
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(Activity context, float bgAlpha) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
    }

    @OnClick({R.id.tv_mid_title, R.id.iv_title_icon})
    public void onClick(View v) {
        pw.showAsDropDown(rlBar);
        backgroundAlpha(BalanceActivity.this, 0.5f);//0.0-1.0
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        pull_list.setMode(PullToRefreshBase.Mode.BOTH);
        page = 1;
        records.clear();
        Data();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        Data();
    }

    @Override
    public void OnRetry(String btnMessage) {
        showLoadingLayout(pull_list);
        Data();
    }
}
